//
//  HJMainController.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "HJMainController.h"
#import "HJMainController.h"
#import "HJNavigationController.h"
#import "HJIM.h"
#import "HJConversationController.h"
#import "HJSwiftJsonAnimationView.h"
#import "HJFriendListController.h"
#import "QMUIRuntime.h"
#import "HJTabBarContentView.h"
#import "HJMineController.h"
#import "HJInformationController.h"


@interface HJMainController ()<HJTabBarContentViewDelegate>

@property (strong, nonatomic) NSArray *tabItemConfigurations;
@property (nonatomic, strong) NSDate *lastDate;
@property (nonatomic, assign) NSInteger lastClickIndex;
@property (nonatomic, strong) HJTabBarContentView *tabBarContentView;
@property (nonatomic, weak) UIView *lastAnimationView;


@end

@implementation HJMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setingTabBar];
    [self addChildViewController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMessageBadgeChangeNotification:) name:messageBadgeChangeNotification object:nil];
    [HJIM.shareIM.conversationManager updateBadge];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUserApplyCountChangeNotification:) name:userApplyCountChangeNotification object:nil];
    
    [HJIM.shareIM.userManager queryUserInfoWithUserId:HJUserInfo.userId complete:^(HJChatUserModel * _Nullable model) {
        [self setTabBarItemBadgeValueWithControllerClass:HJFriendListController.class badgeValue:model.applyCount.intValue];
    }];
}

- (void)handleUserApplyCountChangeNotification:(NSNotification *)not {
    NSInteger badgeValue = [not.object intValue];
    badgeValue = MIN(99, badgeValue);
    [self setTabBarItemBadgeValueWithControllerClass:HJFriendListController.class badgeValue:badgeValue];
}

- (void)handleMessageBadgeChangeNotification:(NSNotification *)not {
    NSInteger badgeValue = [not.object intValue];
    badgeValue = MIN(99, badgeValue);
    UIApplication.sharedApplication.applicationIconBadgeNumber = badgeValue;
    [self setTabBarItemBadgeValueWithControllerClass:HJConversationController.class badgeValue:badgeValue];
}

- (void)setingTabBar {
    
    self.tabBar.translucent = NO;
    
    TJWeakify(self)
    ExtendImplementationOfVoidMethodWithoutArguments(UITabBar.class, @selector(layoutSubviews), ^(__kindof NSObject *selfObject) {
        
        for (UIView *subView in weakself.tabBar.subviews) {
            if (![subView isKindOfClass:HJTabBarContentView.class]) {
                [subView removeFromSuperview];
            }
        }
        
        HJTabBarContentView *tabBarContentView = weakself.tabBar.subviews.firstObject;
        if (!tabBarContentView) {
            tabBarContentView = [[HJTabBarContentView alloc] initWithDatas:weakself.tabItemConfigurations];
            weakself.tabBarContentView = tabBarContentView;
            [weakself.tabBar addSubview:tabBarContentView];
        }
        tabBarContentView.backgroundColor = UIColor.whiteColor;
        tabBarContentView.delegate = weakself;
        tabBarContentView.frame = weakself.tabBar.bounds;
    });
}

- (void)tj_setSelectedIndex:(NSUInteger)selectedIndex {
    self.selectedIndex = selectedIndex;
    [self.tabBarContentView selectIndex:selectedIndex];
}

- (void)tabBar:(HJTabBarContentView *)tabBar didSelectButton:(HJTabBarButton *)button index:(NSInteger)index {
    self.selectedIndex = index;

    if (_lastAnimationView) {
        _lastAnimationView.hidden = NO;
        [_lastAnimationView.superview.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:HJSwiftJsonAnimationView.class]) {
                HJSwiftJsonAnimationView *lastLottieAnimationView = (HJSwiftJsonAnimationView *)obj;
                [lastLottieAnimationView stop];
                [lastLottieAnimationView removeFromSuperview];
                lastLottieAnimationView = nil;
            }
        }];
    }
    
    UIView *currentAnimationView = button.imageView;
    _lastAnimationView = currentAnimationView;
    
    NSDictionary *dict = self.tabItemConfigurations[index];
    
    __block HJSwiftJsonAnimationView *lottieAnimationView = [[HJSwiftJsonAnimationView alloc] initWithName:dict[@"jsonName"]];
    lottieAnimationView.frame = currentAnimationView.bounds;
    lottieAnimationView.center = currentAnimationView.center;
    [currentAnimationView.superview addSubview:lottieAnimationView];
    [button bringSubviewToFront:button.unReadView];
    currentAnimationView.hidden = YES;
    [lottieAnimationView playComplete:^(BOOL res) {
        if (res) {
            currentAnimationView.hidden = NO;
            [lottieAnimationView removeFromSuperview];
            lottieAnimationView = nil;
        }
    }];
}

- (void)setTabBarItemBadgeValueWithControllerClass:(Class)class badgeValue:(NSInteger)badgeValue  {
    
    __block NSInteger badgeIndex = 0;
    [self.childViewControllers enumerateObjectsUsingBlock:^(__kindof UINavigationController * _Nonnull conversationNavController, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([conversationNavController.viewControllers.firstObject isKindOfClass:class]) {
            badgeIndex = idx;
            *stop = YES;
        }
    }];
    
    HJTabBarButton *tabBarButton = [self.tabBarContentView buttonWithIndex:badgeIndex];
    tabBarButton.badgeValue = badgeValue;
}

- (void)addChildViewController {
    [self.tabItemConfigurations enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self addChildViewController:obj[@"controller"] image:obj[@"iconName"]  selectImage:obj[@"selectIconName"] title:obj[@"title"]];
    }];
}

- (void)addChildViewController:(UIViewController *)childController image:(NSString *)image  selectImage:(NSString *)selectImage title:(NSString *)title {
    
    HJNavigationController *navigationController = [[HJNavigationController alloc] initWithRootViewController: childController];
    navigationController.view.backgroundColor = [UIColor whiteColor];
    [self addChildViewController: navigationController];
    childController.title = title;
    childController.navigationItem.title = title;
    childController.tabBarItem.image = [UIImage imageNamed:image];
    childController.tabBarItem.selectedImage = [UIImage imageNamed:selectImage];
}

- (NSArray *)tabItemConfigurations {
    if (!_tabItemConfigurations) {
        _tabItemConfigurations = @[
            @{
                @"controller": [[HJConversationController alloc] init],
                @"iconName": @"chat",
                @"selectIconName": @"chat_select_icon",
                @"title": @"Chats",
                @"jsonName": @"chat"
            },
            @{
                @"controller": [[HJFriendListController alloc] init],
                @"iconName": @"friends",
                @"selectIconName": @"friends_select_icon",
                @"title": @"Friends",
                @"jsonName": @"Friends"
            },
            @{
                @"controller": [[HJInformationController alloc] init],
                @"iconName": @"DApp",
                @"selectIconName": @"DApp_select_icon",
                @"title": @"News",
                @"jsonName": @"dapp"
            },
            @{
                @"controller": [[HJMineController alloc] init],
                @"iconName": @"me",
                @"selectIconName": @"me_select_icon",
                @"title": @"Me",
                @"jsonName": @"me"
            }
        ];
    }
    return _tabItemConfigurations;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
